<template>
  <div class="all">
    <van-nav-bar
      fixed
      placeholder
      safe-area-inset-top
      title="客服"
      @click-left="back"
    >
      <template #left>
        <van-icon name="arrow-left" size="16px" color="#333" />
      </template>
    </van-nav-bar>
    <div ref="content" class="bigbox">
      <div
        v-for="(item, index) in getCurrentRecord"
        :key="index"
        class="chatbox"
      >
        <div v-if="item.messageType === $imlib.MESSAGE_TYPE.TEXT">
          <div class="time">
            <span>{{ item.time }}</span>
          </div>
          <div class="chatcontent">
            <div class="head">
              <van-image
                v-show="
                  item.type === $imlib.CONVERSATION_TYPE.PRIVATE &&
                  item.messageDirection === 2
                "
                round
                width="50px"
                height="50px"
                :src="item.avatar"
              />
            </div>
            <div class="chattwo">{{ item.content }}</div>
            <div class="head">
              <van-image
                v-show="
                  item.type === $imlib.CONVERSATION_TYPE.PRIVATE &&
                  item.messageDirection === 1
                "
                round
                width="50px"
                height="50px"
                :src="item.avatar"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="sendchat">
      <input
        v-model="sendwords"
        type="text"
        placeholder="请输入您想要的说的话"
      />
      <button @click="send">发送</button>
    </div>
    <div class="safe" />
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getUserInfo } from "../../apis/user";
import { baseUtils } from "@/utils/baseUtils";
import local from "../../utils/local";
import { getSecret, getLoginStatus } from "@/utils/auth";
export default {
  data() {
    return {
      sendwords: "",
      targetId: null,
      conversation: {},
      list: [],
      dialogVisible: false,
      messageid: "",
      sentTime: 0,
      hasMore: false,
      avatar: "",
    };
  },
  computed: {
    ...mapGetters(["record", "connect", "historyTimestamp"]),
    getHasMore() {
      return this.$store.getters.hasMore;
    },
    getCurrentRecord() {
      return this.record[this.targetId];
    },
  },
  watch: {
    getHasMore(val) {
      this.hasMore = val;
      if (val) {
        this.loadMore();
      }
    },
  },
  created() {
    const secret = getSecret();
    this.targetId = this.$route.query.targetId;
    this.avatar = secret.avatar;
    // 登录状态
    const isLogin = getLoginStatus();
    if (this.connect === true && isLogin === true) {
      // 获取指定会话的抽象实例，对于会话的操作基于此实例完成
      this.conversation = this.$im.Conversation.get({
        // targetId
        targetId: this.targetId,
        // 会话类型：RongIMLib.CONVERSATION_TYPE.PRIVATE  单聊
        type: this.$imlib.CONVERSATION_TYPE.PRIVATE,
      });

      // this.clearUnread();
      const targetId = this.targetId;
      const record = this.record;
      const option = {
        // 获取历史消息的时间戳，默认为 0，表示从当前时间获取
        timestamp: +new Date(),
        // 获取条数，有效值 1-20，默认为 20
        count: 20,
      };
      // 历史消息
      this.conversation
        .getMessages(option)
        .then((result) => {
          // 获取到的消息列表
          const list = result.list;
          const hasMore = result.hasMore;
          console.log("获取历史消息成功", list, hasMore);
          const historyTimestamp = list[0].sentTime - 1;

          this.$store.dispatch("im/setHasMore", { hasMore: hasMore });
          this.$store.dispatch("im/setHistoryTimestamp", {
            historyTimestamp: historyTimestamp,
          });

          if (list.length > 0) {
            record[targetId] = [];
            for (const item of list) {
              const obj = {};
              const messageType = item.messageType;
              const senderUserId = item.senderUserId;

              switch (messageType) {
                case this.$imlib.MESSAGE_TYPE.TEXT:
                  obj.content = item.content.content;
                  break;
                case this.$imlib.MESSAGE_TYPE.IMAGE:
                  obj.content = item.content.imageUri;
                  break;
                default:
              }

              obj.messageType = messageType;
              obj.time = baseUtils.formatDate(item.sentTime);
              // 消息类型
              obj.type = item.type;
              // 消息方向 发送: 1, 接收: 2
              obj.messageDirection = item.messageDirection;
              obj.messageUId = item.messageUId;
              obj.sentTime = item.sentTime;
              obj.avatar =
                item.messageDirection === 1
                  ? this.avatar
                  : this.$store.getters.conversation[senderUserId].avatar;
              record[targetId].push(obj);
            }
          }
          const newrecord = Object.assign({}, record);
          this.$store.dispatch("im/setRecord", { record: newrecord });
        })
        .catch((error) => {
          console.log("获取历史消息失败", error);
        });
    }
  },
  mounted() {
    setTimeout(() => {
      this.$refs.content.scrollTop = 10000000000;
    }, 100);
  },
  beforeUpdate() {
    setTimeout(() => {
      this.$refs.content.scrollTop = 1000000000000000;
    }, 0);
  },
  methods: {
    back() {
      this.$router.go(-1);
    },
    send() {
      if (this.sendwords) {
        const store = this.$store;
        const imlib = this.$imlib;
        const record = this.record;
        const targetId = this.targetId;
        this.conversation
          .send({
            // 填写开发者定义的 messageType
            messageType: imlib.MESSAGE_TYPE.TEXT,
            // 消息内容
            content: {
              content: this.sendwords,
              extra: { avatar: this.avatar },
            },
            // 是否存储在服务端,默认为 true
            isPersited: true,
            // 是否计数. 计数消息接收端接收后未读数加 1，默认为 true
            isCounted: true,
            // 设置为 true 后 isPersited 和 isCounted 属性失效
            isStatusMessage: false,
            // 设置为 true 后移动端不会收到 Push 信息和本地通知提醒
            disableNotification: false,
          })
          .then((message) => {
            // 消息成成功更新 record
            const obj = {};
            const messageType = message.messageType;
            const senderUserId = message.senderUserId;

            switch (messageType) {
              case imlib.MESSAGE_TYPE.TEXT:
                obj.content = message.content.content;
                break;
              case imlib.MESSAGE_TYPE.IMAGE:
                obj.content = message.content.imageUri;
                break;
              default:
            }

            obj.messageType = messageType;
            obj.time = baseUtils.formatDate(message.sentTime);
            // 消息类型
            obj.type = message.type;
            // 消息方向 发送: 1, 接收: 2
            obj.messageDirection = message.messageDirection;
            obj.messageUId = message.messageUId;
            obj.sentTime = message.sentTime;
            obj.avatar =
              message.messageDirection === 1
                ? this.avatar
                : store.getters.conversation[senderUserId].avatar;
            if (record[targetId]) {
              record[targetId].push(obj);
            } else {
              record[targetId] = [];
              record[targetId].push(obj);
            }
            const newrecord = Object.assign({}, record);
            store.dispatch("im/setRecord", { record: newrecord });
            this.sendwords = "";
          });
      } else {
        this.$toast("发送消息为空");
      }
    },
    async clearUnread() {
      // 清除未读消息数 im.watch conversation 将被触发
      const store = this.$store;
      const targetId = this.targetId;
      this.conversation.read().then(() => {
        const list = store.getters.conversation;
        list[targetId].unreadCount = 0;
        store.dispatch("im/setConversation", {
          conversation: list,
        });
      });
    },
    loadMore() {
      const record = this.record;
      const targetId = this.targetId;
      const timestamp = this.historyTimestamp;
      const option = {
        // 获取历史消息的时间戳，默认为 0，表示从当前时间获取
        timestamp: timestamp,
        // 获取条数，有效值 1-20，默认为 20
        count: 20,
      };
      // 历史消息
      this.conversation
        .getMessages(option)
        .then((result) => {
          // 获取到的消息列表
          // 倒序
          const list = result.list.reverse();
          const hasMore = result.hasMore;
          const historyTimestamp = list[0].sentTime - 1;

          this.$store.dispatch("im/setHistoryTimestamp", {
            historyTimestamp: historyTimestamp,
          });
          this.$store.dispatch("im/setHasMore", { hasMore: hasMore });

          if (list.length > 0) {
            for (const item of list) {
              const obj = {};
              const messageType = item.messageType;
              const senderUserId = item.senderUserId;

              switch (messageType) {
                case this.$imlib.MESSAGE_TYPE.TEXT:
                  obj.content = item.content.content;
                  break;
                case this.$imlib.MESSAGE_TYPE.IMAGE:
                  obj.content = item.content.imageUri;
                  break;
                default:
              }

              obj.messageType = messageType;
              obj.time = baseUtils.formatDate(item.sentTime);
              // 消息类型
              obj.type = item.type;
              // 消息方向 发送: 1, 接收: 2
              obj.messageDirection = item.messageDirection;
              obj.messageUId = item.messageUId;
              obj.sentTime = item.sentTime;
              obj.avatar =
                item.messageDirection === 1
                  ? this.avatar
                  : this.$store.getters.conversation[senderUserId].avatar;
              // 前一位
              record[targetId].splice(0, 0, obj);
            }
          }
          this.$store.dispatch("im/setRecord", { record: record });
        })
        .catch((error) => {
          console.log("获取历史消息失败", error.code, error.msg);
        });
    },
  },
};
</script>

<style lang="less" scoped>
.all {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f2f2f2 !important;
}
.bigbox {
  padding-top: 15px;
  overflow-y: scroll;
  // background-color: #f2f2f2;
  flex: 1;
  .time {
    text-align: center;
    span {
      background-color: #cdcdcd;
      display: inline-block;
      color: #fff;
      font-size: 13px;
      padding: 2px 7px;
      border-radius: 10px;
    }
  }
  .chatcontent {
    width: 100%;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-around;
    padding: 15px;
    .head {
      width: 50px;
    }
    .chattwo {
      box-sizing: border-box;
      font-size: 15px;
      width: 60%;
      background-color: #fff;
      padding: 10px 20px;
      word-wrap: break-word;
      word-break: break-all;
      overflow: hidden;
    }
  }
}

.sendchat {
  position: fixed;
  bottom: 0;
  width: 100vw;
  display: flex;
  justify-content: space-evenly;
  padding: 15px;
  background-color: #f6f6f6;
  input {
    border: none;
    padding-left: 10px;
    color: #333;
    font-size: 14px;
    width: 60%;
    height: 33px;
  }
  button {
    width: 60px;
    height: 33px;
    border-radius: 16px;
    font-size: 14px;
    background-color: #45b7cb;
    color: #fff;
    border: none;
  }
}
.safe {
  background-color: #f6f6f6;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
</style>
